/*
 * Copyright 2020-2030, MateCloud, DAOTIANDI Technology Inc All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * Author: pangu(7333791@qq.com)
 */
package com.yc.cloud.admin.controller;

import cn.hutool.core.collection.CollUtil;
import com.yc.cloud.admin.common.UmsAdminConstants;
import com.yc.cloud.admin.dto.request.UmsAdminUpdateParam;
import com.yc.cloud.admin.dto.request.UpdateAdminPasswordParam;
import com.yc.cloud.admin.service.UmsAdminService;
import com.yc.cloud.admin.service.UmsMenuService;
import com.yc.cloud.admin.service.UmsRoleService;
import com.yc.cloud.common.basic.api.ResponseResult;
import com.yc.cloud.common.basic.dto.BasePageReqDTO;
import com.yc.cloud.common.basic.exception.Asserts;
import com.yc.cloud.common.orm.CommonPage;
import com.yc.cloud.entity.UmsAdmin;
import com.yc.cloud.entity.UmsRole;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.val;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 后台用户表 前端控制器
 * </p>
 *
 * @author JackGu
 * @since 2022-09-11
 */
@RestController
@RequestMapping("/admin")
@Api(value = "后台用户表", tags = "后台用户表接口")
public class UmsAdminController {

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Resource
    private UmsAdminService umsAdminService;

    @Resource
    private UmsAdminService adminService;

    @Resource
    private UmsRoleService roleService;

    @Resource
    private UmsMenuService umsMenuService;

    @GetMapping("/list")
    @ApiOperation(value = "列表", notes = "支持分页查询,字段模糊匹配,排序等")
    public ResponseResult<CommonPage<UmsAdmin>> list(BasePageReqDTO param) {
        val result = umsAdminService.list(param);
        return ResponseResult.success(CommonPage.restPage(result));
    }


    @GetMapping("/{id}")
    @ApiOperation(value = "详情", notes = "根据ID查询")
    public ResponseResult<UmsAdmin> getItem(@PathVariable @ApiParam(value = "ID", required = true) Long id) {
        return ResponseResult.success(umsAdminService.getById(id));
    }


    @PostMapping("/create")
    @ApiOperation(value = "添加", notes = "添加后台用户表")
    public ResponseResult<UmsAdmin> create(@Validated @RequestBody UmsAdmin umsAdmin) {
        val result = umsAdminService.create(umsAdmin);
        if (result != null) {
            return ResponseResult.success(result);
        }
        return ResponseResult.failed();
    }


    @ApiOperation(value = "删除", notes = "通过ID删除")
    @PostMapping(value = "/delete/{id}")
    public ResponseResult<Long> delete(@PathVariable @ApiParam(value = "ID", required = true) Long id) {
        val result = umsAdminService.removeById(id);
        if (result) {
            return ResponseResult.success();
        }
        return ResponseResult.failed();
    }


    @PostMapping("/delete/batch")
    @ApiOperation(value = "批量删除", notes = "通过id逗号分隔,批量删除")
    public ResponseResult<List<Long>> delete(@RequestParam List<Long> ids) {
        val result = umsAdminService.removeByIds(ids);
        if (result) {
            return ResponseResult.success();
        }
        return ResponseResult.failed();
    }


    @ApiOperation(value = "修改", notes = "通过ID修改")
    @PostMapping(value = "/update/{id}")
    public ResponseResult<Long> update(@PathVariable @ApiParam(value = "ID", required = true) Long id, @Validated @RequestBody UmsAdminUpdateParam umsAdmin) {
        val result = umsAdminService.update(id, umsAdmin);
        if (result > 0) {
            return ResponseResult.success();
        }
        return ResponseResult.failed();
    }


    @ApiOperation(value = "获取当前登录用户信息")
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    @ResponseBody
    public ResponseResult<Map<String, Object>> getAdminInfo() {
        UmsAdmin umsAdmin = umsAdminService.getAdmin();
        Map<String, Object> data = new HashMap<>(4);
        data.put("username", umsAdmin.getUsername());
        data.put("menus", umsMenuService.getMenuList(umsAdmin.getId()));
        data.put("icon", umsAdmin.getIcon());
        List<UmsRole> roleList = roleService.getRoleList(umsAdmin.getId());
        if (CollUtil.isEmpty(roleList)) {
            Asserts.fail(UmsAdminConstants.USER_ROLE_EMPTY);
        }
        if (CollUtil.isNotEmpty(roleList)) {
            List<String> roles = roleList.stream().map(UmsRole::getName).collect(Collectors.toList());
            data.put("roles", roles);
        }
        return ResponseResult.success(data);
    }

    @ApiOperation("给用户分配角色")
    @RequestMapping(value = "/role/update", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult<Integer> updateRole(@RequestParam("adminId") Long adminId, @RequestParam("roleIds") List<Long> roleIds) {
        int count = roleService.updateRole(adminId, roleIds);
        if (count >= 0) {
            return ResponseResult.success(count);
        }
        return ResponseResult.failed();
    }

    @ApiOperation("获取指定用户的角色")
    @RequestMapping(value = "/role/{adminId}", method = RequestMethod.GET)
    @ResponseBody
    public ResponseResult<List<UmsRole>> getRoleList(@PathVariable Long adminId) {
        List<UmsRole> roleList = roleService.getRoleList(adminId);
        return ResponseResult.success(roleList);
    }


    @ApiOperation(value = "登出功能")
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult<String> logout() {
        adminService.logout();
        return ResponseResult.success("登出成功");
    }


    @ApiOperation("修改指定用户密码")
    @RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult<Integer> updatePassword(@Validated @RequestBody UpdateAdminPasswordParam updatePasswordParam) {
        int status = adminService.updatePassword(updatePasswordParam);
        if (status > 0) {
            return ResponseResult.success(status);
        } else if (status == -1) {
            return ResponseResult.failed("提交参数不合法");
        } else if (status == -2) {
            return ResponseResult.failed("找不到该用户");
        } else if (status == -3) {
            return ResponseResult.failed("旧密码错误");
        } else {
            return ResponseResult.failed();
        }
    }


    @ApiOperation("修改帐号状态")
    @RequestMapping(value = "/updateStatus/{id}", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult updateStatus(@PathVariable Long id, @RequestParam(value = "status") Integer status) {
        UmsAdmin umsAdmin = new UmsAdmin();
        umsAdmin.setStatus(status);
        umsAdmin.setId(id);
        if (adminService.updateById(umsAdmin)) {
            return ResponseResult.success();
        }
        return ResponseResult.failed();
    }

    @ApiOperation(value = "刷新token")
    @RequestMapping(value = "/refreshToken", method = RequestMethod.GET)
    @ResponseBody
    public ResponseResult refreshToken(HttpServletRequest request) {
        String token = request.getHeader(tokenHeader);
        String refreshToken = adminService.refreshToken(token);
        if (refreshToken == null) {
            return ResponseResult.failed("token已经过期！");
        }
        val result = tokenHead + refreshToken;
        return ResponseResult.success(result);
    }

}
